var superagent=require('superagent')
var async=require('async')
var cheerio=require('cheerio')
var eventproxy=require('eventproxy')
var ep=new eventproxy()
var mongoose=require('mongoose')
var mongourl='mongod://127.0.0.1:27017'

mongoose.Promise=global.Promise;
mongoose.connect(mongourl,{useMongoClient:true});
var Schema=mongoose.Schema;
var DesignSchema=new Schema({
    1:String
})
var Design=mongoose.model('Design',DesignSchema)


var designUrl='http://www.mogooo.com/cases.aspx'
var yijiUrl=[]
var erjiUrl=[]
superagent.get(designUrl)
    .end(function(err,res){
        if(err)
            console.error('错误')
        else{
            var $=cheerio.load(res.text)
            getErji($)
        }
    })

    function getErji($){
        for(var i=0;i<$(".caseclass a").length;i++){
            yijiUrl.push('http://www.mogooo.com'+$(".caseclass a").eq(i).attr('href'))
        }
        yijiUrl.forEach(function(yiji){
            superagent.get(yiji)
            .end(function(err,res){
                var $=cheerio.load(res.text)
                ep.emit('second',[yiji,res.text])
            })
        })
        ep.after('second',yijiUrl.length,function(list){
            var oneRepo = list.map(function (repo) {
                var repoUrl = repo[0]
                var repoHTMl = repo[1]
                var $ = cheerio.load(repoHTMl)
                for(var i=0;i<$(".casebox a").length;i++){
                    erjiUrl.push('http://www.mogooo.com/'+$(".casebox a").eq(i).attr("href"))
                }
            })
            getSanji()
        })
    }
    function getSanji(){
        erjiUrl.forEach(function(erji){
            superagent.get(erji)
            .end(function(err,res){
                var $=cheerio.load(res.text)
                ep.emit('third',[erji,res.text])
            })
        })
        
        ep.after('third',5,function(list){
            var oneRepo = list.map(function (repo) {
                var repoUrl = repo[0]
                var repoHTMl = repo[1]
                var $ = cheerio.load(repoHTMl)
                for(var i=0;i<$(".casebox a").length;i++){
                    sanjiUrl.push('http://www.mogooo.com/'+$(".casebox a").eq(i).attr("href"))
                }
            })
        })
    }













